package com.aaron.config;

import com.aaron.io.Resources;
import com.aaron.pojo.Configuration;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是使用dom4j配置文件进行解析,封装configuration
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws Exception {
        //
        Document document = new SAXReader().read(inputStream);
        //<configuration>
        Element rootElement = document.getRootElement();
        Properties properties = new Properties();
        List<Element> list = rootElement.selectNodes("//property");
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        //new 一个数据源对象
//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
//        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
//        comboPooledDataSource.setUser(properties.getProperty("userName"));
//        comboPooledDataSource.setPassword(properties.getProperty("password"));
//        configuration.setDataSource(comboPooledDataSource);

        Properties propertiesDruid = new Properties();
        propertiesDruid.setProperty("url",properties.getProperty("jdbcUrl"));
        propertiesDruid.setProperty("username",properties.getProperty("userName"));
        propertiesDruid.setProperty("password",properties.getProperty("password"));
        propertiesDruid.setProperty("driverClassName",properties.getProperty("driverClass"));
        configuration.setDataSource(DruidDataSourceFactory.createDataSource(propertiesDruid));


        //解析Mapper.xml: 拿到路径---字节输入流--dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }
}
